package com.cicc.wm.lock.jdbc;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.cicc.wm.lock.config.LockProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * jdbcLock自动配置
 */
@Configuration
@ConditionalOnClass(DataSource.class)
@EnableConfigurationProperties(LockProperties.class)
public class JdbcLockAutoConfiguration {

    @Bean
    public JdbcLockRepository jdbcLockRepository(DataSource dataSource, LockProperties lockProperties) {
        JdbcLockRepository jdbcLockRepository = new JdbcLockRepository(dataSource);
        if (CharSequenceUtil.isNotBlank(lockProperties.getJdbc().getTablePrefix())) {
            jdbcLockRepository.setPrefix(lockProperties.getJdbc().getTablePrefix());
        }
        jdbcLockRepository.setRegion(SpringUtil.getApplicationName());
        return jdbcLockRepository;
    }

    @Bean
    @ConditionalOnBean(JdbcLockRepository.class)
    public JdbcLockRegistry jdbcLockRegistry(JdbcLockRepository jdbcLockRepository) {
        return new JdbcLockRegistry(jdbcLockRepository);
    }
}
